<script setup lang="ts">
import { unref, ref, PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { ElForm, ElFormItem, ElRow, ElCol, ElButton, FormInstance } from 'element-plus'

const props = defineProps({
  getSearchFormData: propTypes.func,
  // 表单label宽度
  labelWidth: propTypes.oneOfType([String, Number]).def('100px'),
  labelPosition: propTypes.string
    .validate((v: string) => ['left', 'right', 'top'].includes(v))
    .def('right'),
  showSearch: propTypes.bool.def(true),
  showReset: propTypes.bool.def(true),
  // 是否显示伸缩
  expand: propTypes.bool.def(false),
  model: {
    type: Object as PropType<Recordable>,
    default: () => ({})
  }
})

const emit = defineEmits(['search', 'reset'])

const visible = ref(true)

const elFormRef = ref<FormInstance>()

const search = async () => {
  await unref(elFormRef)?.validate((isValid) => {
    if (isValid) {
      emit('search', props.model)
    }
  })
}

const reset = async () => {
  unref(elFormRef)?.resetFields()
  emit('reset', props.model)
}

const setVisible = () => {
  unref(elFormRef)?.resetFields()
  visible.value = !unref(visible)
}
</script>

<template>
  <ElForm
    :model="model"
    ref="elFormRef"
    :label-width="labelWidth"
    label-position="right"
    hide-required-asterisk
    :validate-on-rule-change="false"
    class="cu-search"
  >
    <ElRow>
      <slot></slot>
      <ElCol style="flex: 1">
        <ElFormItem labelWidth="0px">
          <div style="width: 100%; display: flex; justify-content: flex-end; padding-right: 10px">
            <ElButton v-if="showSearch" type="primary" @click="search">
              <Icon icon="ep:search" class="mr-5px" />
              查询
            </ElButton>
            <ElButton v-if="showReset" @click="reset">
              <Icon icon="ep:refresh-right" class="mr-5px" />
              重置
            </ElButton>
            <ElButton v-if="expand" text @click="setVisible">
              {{ visible ? '收起' : '展开' }}
              <Icon :icon="visible ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
            </ElButton>
          </div>
        </ElFormItem>
      </ElCol>
    </ElRow>
  </ElForm>
</template>

<style lang="less" scoped>
.cu-search {
  background-color: #ffffff;
  padding: 20px 20px 0 20px;
  border-radius: 2px;
}
</style>
